import axios from 'axios'
import {
  Toast,Dialog 
} from 'vant'
import { getToken } from '@/utils/auth'
import store from '@/store'
import Router from '@/router/index'

//getToken("UserToken")  获取不到HttpOnly的cookie
axios.defaults.withCredentials = true  //前端跨域传递Cookie
const CancelToken = axios.CancelToken
const pending = []

const instance = axios.create({
 
  timeout: 50000,
  headers: {
    'Content-Type':'application/json; charset=utf-8',
  }
})
instance.interceptors.request.use(config => {
  // 在请求发送前做的操作
  config.headers['authorization'] = localStorage.getItem('authorization')
  config.cancelToken = new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    pending.push(c)
  })
  return config
},
error => {
  // do something with request error
  Toast.fail('请求错误');
  return Promise.reject(error)
})


instance.interceptors.response.use(response => {
  const res = response.data;//res对应nodejson返回值 res.json(res)
  if(res.resultCode !==200){
    
    if(res.resultCode === 416){
      Toast.fail(res.message);
      localStorage.removeItem('authorization');
    }else if(res.resultCode === 403){
      //未登录,登录失效
      Toast.fail(res.message);
    }else{
      Toast.fail(res.message);
    }
    return Promise.reject(res.message || 'Error')
  }else{
    return res; 
  }
},err => {
  console.log("err"+err);
  Toast.fail(err.message);
  return Promise.reject(err); 
})



export default instance 